import { MapData, Block } from "../Data/MapData";
import { level7_data } from "../Data/Levels/level7";
import CharView from "./CharView";

const {ccclass, property} = cc._decorator;

@ccclass
export default class MapView extends cc.Component {

    @property(cc.Prefab)
    charPrefab : cc.Prefab = null;

    public selCharView : CharView = null;

    // LIFE-CYCLE CALLBACKS:

    static instance : MapView = null;

    onLoad () {
        MapView.instance = this;
    }

    CreateCharView(row:number, col:number, parent:cc.Node):CharView{
        let mapData = MapData.GetInstance().data; // shortcut
        let block : Block = mapData[row][col];
        let charNode : cc.Node = cc.instantiate(this.charPrefab);
        charNode.name = `R${row}C${col}`;
        charNode.setParent(this.node);

        let charView : CharView = charNode.getComponent(CharView);

        // 建立双向关联
        block.mapCharView = charView;
        charView.blockData = block;

        charView.char = block.char;
        charView.isGray = block.isGray;
        charView.isHidden = block.isHidden;

        return charView;
    }

    start () {
        // TODO: 按照地图数据，创建字块预制体，并设置其属性
        MapData.GetInstance().LoadLevel(level7_data);

        let mapData = MapData.GetInstance().data; // shortcut

        for (let row = 0; row < mapData.length; row++)
        {
            for (let col = 0; col < mapData[row].length; col++)
            {
                let charView = this.CreateCharView(row,col,this.node);

                if (this.selCharView == null && charView.isHidden){
                    charView.isSelected = true;
                    this.selCharView = charView;
                }

                if (charView.isHidden){
                    charView.node.on(cc.Node.EventType.MOUSE_UP, ()=>{
                        // console.log(`你点中了(${row},${col})节点`);
                        // this.foo();
                        this.selCharView.isSelected = false;
                        charView.isSelected = true;
                        this.selCharView = charView;
                    });
                }
            }
        }
    }

    // update (dt) {}
}
